const { perfromSql, send, sendErr, getToken } = require('../utils/index');
const express = require('express');
const route = express.Router();

route.post('/api/getNotes', async (req, res) => {
    const { page_num, page_size, search } = req.body //当前的页数
    let result = null
    let results = null
    if (!search) {
        const sql = `select n.*,u.\`name\`
        from note as n
        left join \`user\` as u on n.uid=u.id
        limit ?,?`
        result = await perfromSql(sql, (parseInt(page_num) - 1) * parseInt(page_size), parseInt(page_size));
        if (result.length === 0) {
            sendErr(res, '未查询到数据');
            return;
        }
        let sqlTotal = 'select count(*) as total from note'
        results = await perfromSql(sqlTotal)
    } else {
        const sql = `select n.*,u.\`name\`
        from note as n
        left join \`user\` as u on n.uid=u.id
        where n.title like '%${search}%'
        limit ?,?`
        result = await perfromSql(sql, (parseInt(page_num) - 1) * parseInt(page_size), parseInt(page_size));
        if (result.length === 0) {
            sendErr(res, '未查询到数据');
            return;
        }
        let sqlTotal = `select count(*) as total from note where title like '%${search}%'`
        results = await perfromSql(sqlTotal)
    }
    //成功
    let total = results[0]['total']
    send(res, {
        data: result,
        total: total,
        page_num: page_num,
        page_size: page_size,
    });
})

route.post('/note/update', async (req, res) => {
    const { id, title, desc, text } = req.body;
    const { id: uid } = req.auth;
    if (!title || !desc || !text) {
        console.error(req.body);
        sendErr(res, '参数错误');
        return;
    }
    let result = null;
    if (id) {
        const updateSql = `update note set ? where id=?`
        result = await perfromSql(updateSql, { title, desc, text }, id);
    } else {
        const addSql = `insert into note set ?`
        result = await perfromSql(addSql, { title, desc, text, uid })
    }
    if (result?.affectedRows == 1) {
        send(res, '成功');
        return;
    }
    sendErr(res, '失败了');
})

route.post('/note/getTextById', async (req, res) => {
    const { id } = req.body;
    if (typeof id != 'number') {
        sendErr(res, '参数错误');
        return;
    }
    const sql = `select text,uid from note where id=? limit 1`;
    let result = await perfromSql(sql, id);
    if (result.length == 1) {
        send(res, result[0]);
        return;
    }
    sendErr(res, '查询失败')
})

route.post('/note/deleteNote', async (req, res) => {
    const { id } = req.body;

    if (typeof id != 'number') {
        sendErr(res, '参数错误');
        return;
    }

    const sql = `delete from note where id = ?`
    let result = await perfromSql(sql, id)
    if (result.affectedRows != 1) {
        sendErr(res, '删除失败')
        return
    }
    send(res, '删除成功')
})
module.exports = route;